<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div id="app">
        <div>父组件</div>
        <button @click='handle'>销毁组件</button>
        <test-tom></test-tom>
        <test-jarry></test-jarry>
    </div>
    <script type="text/javascript" src="../js/vue.js"></script>
    <script type="text/javascript">
        // 提供事件中心
        var hub = new Vue();

        Vue.component('test-tom', {
            data: function() {
                return {
                    num: 0
                }
            },
            template: `
            <div>
                <div>tom:{{num}}</div>
                <div> 
                    <button @click='handle'>点击</button>
                </div>
            </div>
            `,
            methods: {
                handle: function() {
                    hub.$emit('jarry-event', 2)
                }
            },
            mounted: function() {
                // 监听事件
                hub.$on('tom-event', (val) => {
                    this.num += val;
                })
            }
        });

        Vue.component('test-jarry', {
            data: function() {
                return {
                    num: 0
                }
            },
            template: `
            <div>
                <div>jarry:{{num}}</div>
                <div> 
                    <button @click='handle'>点击</button>
                </div>  
            </div>
            `,
            methods: {
                handle: function() {
                    // 触发兄弟组件
                    hub.$emit('tom-event', 1)
                }
            },
            mounted: function() {
                // 监听事件
                hub.$on('jarry-event', (val) => {
                    this.num += val;
                })
            }
        });

        var m = new Vue({
            el: '#app',
            data: {

            },
            methods: {
                handle: function() {
                    hub.$off('tom-event')
                    hub.$off('jarry-event')
                }
            }
        })
    </script>
</body>

</html>